import pymysql


class DB:
    def __init__(self, host='localhost', user='root', password='root', dbname='test', charset='utf8', port=3306):
        # 构造数据库连接对象
        self.__conn = pymysql.connect(host=host, user=user, password=password, database=dbname, charset=charset,
                                      port=port)
        # 获取游标对象
        self.__cursor = self.__conn.cursor()

    def __del__(self):
        # 关闭游标对象和连接对象
        self.__cursor.close()
        self.__conn.close()

    def read(self, sql):
        try:
            rows = self.__cursor.execute(sql)
            results = self.__cursor.fetchall()
            return rows, results
        except Exception as e:
            print(e)

    def write(self, sql):
        try:
            rows = self.__cursor.execute(sql)
            self.__conn.commit()
            return rows
        except Exception as e:
            print(e)
            self.__conn.rollback()
            return 0